from datetime import datetime
import os,json,time
import urllib
import urllib.request
def listDir(path,extensions,reuslts = []):
    for x in os.listdir(path):
        filepath = path+"/"+x
        if os.path.isfile(filepath):
            for e in extensions:
                if x.endswith("."+e):
                    reuslts.append(filepath)
                    break
        elif os.path.isdir(filepath):
            listDir(filepath,extensions=extensions,reuslts=reuslts)
        else:
            print(f'other====:{filepath}')
    return reuslts
def accessConfigToDelayTimeout(authorization,areaId,name):
# try:
    
    f = urllib.request.Request("https://lzpt.hnzx.gov.cn/platform-lzt/changearea",headers={
        "Accept": "application/json, text/plain, */*",
        "Authorization": authorization,
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh-Hans;q=0.9",
        "Host": "lzpt.hnzx.gov.cn",
        "Origin": "https://lzpt.hnzx.gov.cn",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15",
        "Referer": "https://lzpt.hnzx.gov.cn/henan-platform/",
        "u-login-areaId": areaId,
        "clientTypeId": "zhengxieplatform"
    })
    r = urllib.request.urlopen(f)
# except urllib.error.URLError as e:
#     print('TIME OUT',e);
# else:
    json1 = {}
    try:
        text = r.read().decode('utf-8')
        json1 = json.loads(text)["data"]
    except:
        json1 = {}
        return f"{name}-json报错"
    return f"{name}-success" if "token" in json1 else f"{name}-outtime"
def reloadCachedData(imageURLs):
    printStr = ""
    for x in imageURLs:
        with open(x, 'rb') as f:
            dic = json.loads(f.read())
            printStr += accessConfigToDelayTimeout(authorization=dic["tokenhenanzxjava"].replace("\"",""),areaId=dic["areaIdhenanzxjava"].replace("\"",""),name=dic["areaNamehenanzxjava"].replace("\"",""))
            updatetime = datetime.fromtimestamp(os.path.getmtime(x)).strftime("%Y-%m-%d %H:%M:%S")
            printStr += f"-{updatetime}\n"
            time.sleep(2)
    return printStr
def updateSession():
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    result = f"{now}\n--------\n"
    basedir = "/Users/wangshuguan/Desktop/sessions"
    if len(os.listdir(basedir)) == 0 :
        result += "----无json文件---\n\n"
    else:
        imageURLs = listDir(basedir, ["json"], reuslts=[])
        result += reloadCachedData(imageURLs)
    result += "-------\n\n"
    with open(f"{basedir}/aa.log.txt", 'a',encoding='utf-8') as f:
        f.write(result)
if __name__ == "__main__":
    updateSession()
    # print(accessConfigToDelayTimeout("authorization","areaId","name"))